<template>
  <v-container class="py-8 d-flex justify-center">
    <v-card class="pa-8" max-width="900" elevation="10" style="width:100%;">
      <v-row>
        <v-col cols="12" md="4" class="d-flex flex-column align-center justify-start pr-md-8 pr-0"
          style="border-right:1px solid #eee;">
          <v-avatar size="120" class="mb-4 mt-4" @click="avatarDialog = true" style="cursor:pointer;">
            <img :src="form.avatar || authStore.avatar" alt="avatar" />
          </v-avatar>
          <div class="mb-2">
            <v-btn size="small" variant="tonal" color="primary" @click="avatarDialog = true">Change avatar</v-btn>
          </div>
          <div class="mt-6 text-center">
            <div class="font-weight-bold text-h6 mb-1">{{ form.username }}</div>
            <div class="grey--text">{{ form.email }}</div>
          </div>
        </v-col>
        <v-col cols="12" md="8">
          <v-tabs v-model="tab" grow class="mb-4">
            <v-tab value="base">Basic information</v-tab>
            <v-tab value="security">Security settings</v-tab>
          </v-tabs>
          <v-window v-model="tab">
            <!-- 基本信息 -->
            <v-window-item value="base">
              <v-form ref="baseFormRef" v-model="baseValid" @submit.prevent="saveBase">
                <v-text-field v-model="form.username" label="Username" disabled prepend-inner-icon="mdi-account"
                  class="mt-2" />
                <v-text-field v-model="form.realName" label="Nickname" prepend-inner-icon="mdi-account-edit"
                  :rules="[(v: string) => !!v || 'Please enter a nickname']" />
                <v-text-field v-model="form.email" label="Email" prepend-inner-icon="mdi-email"
                  :rules="[validateEmail]" />
                <v-text-field v-model="form.mobile" label="Mobile" prepend-inner-icon="mdi-cellphone"
                  :rules="[validateMobile]" placeholder="Please enter a mobile number, only numbers" />
                <v-textarea v-model="form.sign" label="My signature" prepend-inner-icon="mdi-pencil" rows="2" />
                <div class="text-center mt-4">
                  <v-btn color="primary" type="submit">Save</v-btn>
                </div>
              </v-form>
            </v-window-item>
            <!-- 安全设置 -->
            <v-window-item value="security">
              <v-list lines="one">
                <v-list-item>
                  <v-list-item-title>Account password</v-list-item-title>
                  <v-list-item-subtitle>Password strength: {{ passwordLevel }}</v-list-item-subtitle>
                  <template #append>
                    <v-btn size="small" variant="text" color="primary" @click="passwordDialog = true">Modify</v-btn>

                    <v-btn size="small" variant="text" :loading="passwordEmailloading" color="primary"
                      @click="passwordEmail()">email</v-btn>

                  </template>
                </v-list-item>
                <v-divider class="my-2" />
                <v-list-item>
                  <v-list-item-title>Email</v-list-item-title>
                  <v-list-item-subtitle>{{ form.email || 'Not bound' }}</v-list-item-subtitle>
                  <template #append>
                    <v-btn size="small" variant="text" color="primary" @click="emailDialog = true">Modify</v-btn>
                  </template>
                </v-list-item>
                <v-divider class="my-2" />
                <v-list-item>
                  <v-list-item-title>Mobile</v-list-item-title>
                  <v-list-item-subtitle>{{ form.mobile || 'Not bound' }}</v-list-item-subtitle>
                  <template #append>
                    <v-btn size="small" variant="text" color="primary" @click="mobileDialog = true">Modify</v-btn>
                  </template>
                </v-list-item>
                <v-divider class="my-2" />
                <!-- Google Authenticator 绑定 -->
                <v-list-item>
                  <v-list-item-title>Google Authenticator</v-list-item-title>

                  <v-list-item-subtitle>
                    <div v-if="googleBindInfo.is2fa === 1">
                      Bound
                      <v-chip color="success" size="small" class="ml-2">Bound</v-chip>
                    </div>
                    <div v-else>
                      Not bound
                      <v-chip color="grey" size="small" class="ml-2">Not bound</v-chip>
                    </div>
                  </v-list-item-subtitle>
                  <template #append>
                    <v-btn size="small" variant="text" color="primary" @click="openGoogleBindDialog">
                      {{ googleBindInfo.is2fa === 0 ? 'Unbind' : 'Bind' }}
                    </v-btn>
                  </template>
                </v-list-item>
              </v-list>
            </v-window-item>
          </v-window>
        </v-col>
      </v-row>
    </v-card>

    <!-- 更换头像弹窗 -->
    <v-dialog v-model="avatarDialog" max-width="400">
      <v-card>
        <v-card-title>Change avatar</v-card-title>
        <v-card-text>
          <v-file-input v-model="avatarFile" label="Select image" accept="image/*" prepend-icon="mdi-image" />
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn color="primary" @click="uploadAvatar">Upload</v-btn>
          <v-btn text @click="avatarDialog = false">Cancel</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 修改密码弹窗 -->
    <v-dialog v-model="passwordDialog" max-width="400">
      <v-card>
        <v-card-title>Modify password</v-card-title>
        <v-card-text>
          <v-form ref="pwdFormRef" v-model="pwdValid" @submit.prevent="updatePassword">
            <v-text-field v-model="pwdForm.oldPassword" label="Old password" type="password"
              :rules="[(v: string) => !!v || 'Please enter the old password']" />
            <v-text-field v-model="pwdForm.newPassword" label="New password" type="password"
              :rules="[(v: string) => !!v || 'Please enter the new password']" />
            <v-text-field v-model="pwdForm.confirmPassword" label="Confirm new password" type="password"
              :rules="[(v: string) => pwdForm.newPassword === v || 'The two passwords are inconsistent']" />
            <div class="text-center mt-4">
              <v-btn color="primary" type="submit">Save</v-btn>
              <v-btn text @click="passwordDialog = false">Cancel</v-btn>
            </div>
          </v-form>
        </v-card-text>
      </v-card>
    </v-dialog>

    <!-- 修改邮箱弹窗 -->
    <v-dialog v-model="emailDialog" max-width="400">
      <v-card>
        <v-card-title>Modify email</v-card-title>
        <v-card-text>
          <v-form ref="emailFormRef" v-model="emailValid" @submit.prevent="updateEmail">
            <v-text-field v-model="emailForm.email" label="New email" :rules="[validateEmail]" />
            <div class="d-flex align-center">
              <div style="flex:1">
                <v-text-field v-model="emailForm.verificationCode" label="Verification code"
                  :rules="[(v: string) => !!v || 'Please enter the verification code']" />
              </div>
              <div class="align-right ml-4"
                style="flex:1;width:100%; height: 100%; display: flex; align-items: center;">
                <v-btn color="primary" @click="sendEmailCode" :loading="emailCodeLoading" style="">Send
                  code</v-btn>
              </div>


            </div>
            <div class="text-center mt-4">
              <v-btn color="primary" type="submit">Save</v-btn>
              <v-btn text @click="emailDialog = false">Cancel</v-btn>
            </div>
          </v-form>
        </v-card-text>
      </v-card>
    </v-dialog>

    <!-- 修改手机号弹窗 -->
    <v-dialog v-model="mobileDialog" max-width="400">
      <v-card>
        <v-card-title>Modify mobile number</v-card-title>
        <v-card-text>
          <v-form ref="mobileFormRef" v-model="mobileValid" @submit.prevent="updateMobile">
            <v-text-field v-model="mobileForm.mobile" label="New mobile number" :rules="[validateMobile]"
              placeholder="Please enter the mobile number, only numbers" />
            <div class="text-center mt-4">
              <v-btn color="primary" type="submit">Save</v-btn>
              <v-btn text @click="mobileDialog = false">Cancel</v-btn>
            </div>
          </v-form>
        </v-card-text>
      </v-card>
    </v-dialog>

    <!-- Google Authenticator 绑定弹窗 -->
    <v-dialog v-model="googleBindDialog" max-width="420">
      <v-card class="pa-6">
        <v-card-title class="text-h6 font-weight-bold mb-2">
          {{ googleBindInfo.is2fa === 1 ? 'Unbind Google Authenticator' : 'Bind Google Authenticator' }}
        </v-card-title>
        <v-card-text>
          <div v-if="googleBindInfo.is2fa === 0">
            <div class="mb-2">Please use Google Authenticator to scan the QR code below:</div>
            <div class="d-flex justify-center mb-2">
              <v-img :src="googleBindInfo.qrCodeUrl" max-width="160" max-height="160" v-if="googleBindInfo.qrCodeUrl" />
            </div>
            <v-text-field v-model="googleBindCode" label="Enter the 6-digit verification code" maxlength="6" />
          </div>
          <div v-else>
            <div class="mb-2">After unbinding, you will not be able to use Google Authenticator for secondary
              verification.
              Are you sure you want to unbind?</div>
            <v-text-field v-model="googleBindCode" label="Enter the 6-digit verification code to confirm unbinding"
              maxlength="6" />
          </div>
        </v-card-text>
        <v-card-actions class="justify-center">
          <v-btn variant="text" @click="googleBindDialog = false">Cancel</v-btn>
          <v-btn color="primary" @click="handleGoogleBind">{{ googleBindInfo.is2fa === 1 ? 'Unbind' : 'Bind' }}</v-btn>

        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-container>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useAuthStore } from '@/stores/auth';
import { doUpload } from '@/api/tool/ossTool';
import { doUpdateAvatar, doUpdateSelf, doUpdatePassword, doUpdateEmail, doUpdateMobile, resetPasswordEmailById, sendEmailCodeByEmail } from '@/api/system/user/userManagement';
import { message } from '@/utils/message';
import { get2FAQrcode, checkCode } from '@/api/system/2fa/2fa';
// 这里假设你有对应的 API 方法，需根据实际项目实现
// import { updateUserInfo, updatePasswordApi, updateEmailApi, updateMobileApi, uploadAvatarApi } from '@/api/user';
import {
  baseURL
} from '@/config/index';
const authStore = useAuthStore();
const tab = ref('base');
const passwordEmailloading = ref(false);
// 基本信息
const baseFormRef = ref();
const baseValid = ref(true);
const emailCodeLoading = ref(false);
async function sendEmailCode() {
  emailCodeLoading.value = true;
  try {
    const res = await sendEmailCodeByEmail({ email: emailForm.email });
    if (res && res.data && res.data.code == 0) {
      message.success('Email code sent successfully');
    } else {
      message.error(res.data.msg);
    }
    emailCodeLoading.value = false;
  } catch (e) {
    emailCodeLoading.value = false;
  }
}

const form = reactive({
  avatar: authStore.avatar,
  username: authStore.username,
  realName: authStore.userInfo.realName || '',
  email: authStore.userInfo.email || '',
  mobile: authStore.userInfo.mobile || '',
  sign: authStore.userInfo.sign || ''
});

function validateEmail(v: string) {
  if (!v) return true;
  return /.+@.+\..+/.test(v) || 'Please enter a valid email address';
}
function validateMobile(v: string) {
  if (!v) return true;
  return /^\d{8,20}$/.test(v) || 'Please enter an 8-20 digit mobile number';
}
async function saveBase() {
  if (!baseValid.value) return;
  try {
    await doUpdateSelf({
      realName: form.realName,
      email: form.email,
      mobile: form.mobile,
      sign: form.sign,
      avatar: form.avatar,
    });
    message.success('Information saved successfully');

    // 可选：刷新用户信息
    // await authStore.fetchUserInfo();
  } catch (e) {
    message.error('Information saved failed');
  }
}

async function passwordEmail() {
  passwordEmailloading.value = true;
  const res = await resetPasswordEmailById({ userId: authStore.userInfo.id });
  if (res && res.data && res.data.code == 0) {
    message.success('Email sent successfully');
  } else {
    message.error('Email sending failed');
  }
  passwordEmailloading.value = false;
}

// 头像上传
const avatarDialog = ref(false);
const avatarFile = ref<File | null>(null);
async function uploadAvatar() {
  if (!avatarFile.value) return;
  const formData = new FormData();
  formData.append('file', avatarFile.value);
  try {
    const { data } = await doUpload(formData);
    if (data && data.fileStoragePath) {
      await doUpdateAvatar({ imgUrl: data.fileStoragePath });
      form.avatar = data.fileStoragePath;
      message.success('Avatar uploaded successfully');
      // 可选：刷新用户信息
      // await authStore.fetchUserInfo();
    }
  } catch (e) {
    message.error('Avatar upload failed');
  }
  avatarDialog.value = false;
}

// 安全设置
const passwordLevel = 'Medium'; // 可根据实际密码强度计算
const passwordDialog = ref(false);
const pwdFormRef = ref();
const pwdValid = ref(true);
const pwdForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});
async function updatePassword() {
  if (!pwdValid.value) return;
  try {
    await doUpdatePassword({
      oldPassword: pwdForm.oldPassword,
      newPassword: pwdForm.newPassword,
      confirmPassword: pwdForm.confirmPassword,
    });
    message.success('Password modified successfully');
  } catch (e) {
    message.error('Password modification failed');
  }
  passwordDialog.value = false;
}

const emailDialog = ref(false);
const emailFormRef = ref();
const emailValid = ref(true);
const emailForm = reactive({
  email: '',
  verificationCode: '',
  certificate: '1'
});
async function updateEmail() {
  if (!emailValid.value) return;
  try {
    let res = await doUpdateEmail({ email: emailForm.email, verificationCode: emailForm.verificationCode, certificate: emailForm.certificate });
    form.email = emailForm.email;
    if (res && res.data && res.data.code == 0) {
      message.success('Email modified successfully');
    } else {
      message.error(res.data.msg);
    }
  } catch (e) {
    message.error(e as string);
  }
  emailDialog.value = false;
}

const mobileDialog = ref(false);
const mobileFormRef = ref();
const mobileValid = ref(true);
const mobileForm = reactive({
  mobile: ''
});
async function updateMobile() {
  if (!mobileValid.value) return;
  try {
    await doUpdateMobile({ mobile: mobileForm.mobile });
    form.mobile = mobileForm.mobile;
    message.success('Mobile number modified successfully');
  } catch (e) {
    message.error('Mobile number modification failed');
  }
  mobileDialog.value = false;
}

const googleBindDialog = ref(false);
const googleBindInfo = reactive({
  is2fa: authStore.userInfo.is2fa == 1 ? 1 : 0, // 是否已绑定
  qrCodeUrl: '', // 二维码图片地址
  secret: '', // 密钥
});
const googleBindCode = ref('');

async function openGoogleBindDialog() {
  googleBindDialog.value = true;
  const res = await get2FAQrcode({});
  if (googleBindInfo.is2fa === 0) {
    try {
      // res.data 为图片URL
      googleBindInfo.qrCodeUrl = baseURL + "/QR?str=" + res.data;
      googleBindInfo.secret = '';
    } catch (e) {
      message.error('Failed to get QR code');
      return;
    }
  }
  googleBindDialog.value = true;
}

async function handleGoogleBind() {
  if (!googleBindCode.value) {
    message.error('Please enter the verification code');
    return;
  }
  if (googleBindInfo.is2fa === 1) {
    // 调用解绑API（如有）
    message.success('Unbinding successful (example)');
    googleBindInfo.is2fa = 0;
    googleBindDialog.value = false;
  } else {
    // 调用checkCode校验验证码
    try {
      const res = await checkCode({ code: googleBindCode.value });
      console.log(res);
      if (res && res.data && res.data.code == 0) {
        message.success('Binding successful');

        //刷新用户信息
        await authStore.getUserInfo();
        googleBindInfo.is2fa = 1;
        googleBindDialog.value = false;

      } else {
        message.error(res && res.data && res.data.msg ? res.data.msg : 'Verification code error');
      }
    } catch (e) {
      message.error('error');
    }
  }
}
</script>